const readlineSync = require('readline-sync');

// 计算信源熵的函数
function calculateEntropy(probabilities) {
    let entropy = 0;
    for (let p of probabilities) {
        if (p > 0) {
            entropy -= p * Math.log2(p); // 计算熵的公式
        }
    }
    return entropy;
}

// 解析输入并进行验证的函数
function parseInput(input) {
    let probabilities = input.split(/[, ]+/).map(Number); // 支持空格或逗号分隔
    let sum = probabilities.reduce((a, b) => a + b, 0);

    // 验证输入是否合法
    if (probabilities.some(isNaN)) {
        console.error("输入无效！请输入有效的数字。");
        process.exit(1);
    }

    if (probabilities.some(p => p < 0 || p > 1)) {
        console.error("概率必须在 0 和 1 之间！");
        process.exit(1);
    }

    if (sum !== 1) {
        console.error("概率总和必须为 1！");
        process.exit(1);
    }

    return probabilities;
}

// 获取用户输入的概率分布
function getUserInput() {
    console.log("请输入信源概率分布: (Ctrl+D 退出输入)");
    let input = readlineSync.question();
    return parseInput(input);
}

// 主程序逻辑
function main() {
    let probabilities;

    if (process.argv.length > 2) {
        const input = process.argv.slice(2).join(' ');
        probabilities = parseInput(input);
    } else {
        probabilities = getUserInput();
    }

    console.log(`p = [${probabilities.join(',')}]`);
    console.log(`h(p) = ${calculateEntropy(probabilities).toFixed(3)} bit`);
}

// 运行程序
main();
